import axios from 'axios'
import {
  aiLearn,
  aiLearnPad,
  dreamQuestionBank,
  SMART_HOMEWORK,
  messageCenter
} from './host'
import { ElMessage } from 'element-plus'

import router from '@/router'

import { useAuthStore } from '../stores'
import { debounce } from '@/utils/debounce.js'

// 为了演示，先暂时写一个作业系统线上请求地址，后期删掉即可
const onlineSmartHomework = 'https://api.ebag.readboy.com/smart-homework'

const http = axios.create({
  headers: {
    'Content-Type': 'application/json'
  }
})

http.interceptors.request.use(config => {
  const { userInfo } = useAuthStore()

  // ai学网token等信息放到请求头中
  if (
    config.url.startsWith(aiLearn) ||
    config.url.startsWith(aiLearnPad) ||
    config.url.startsWith(dreamQuestionBank) ||
    config.url.startsWith(SMART_HOMEWORK) ||
    config.url.startsWith(onlineSmartHomework) ||
    config.url.startsWith(messageCenter)
  ) {
    config.headers = {
      ...config.headers,
      token: userInfo.sessionId,
      user_id: userInfo.userId,
      platform: userInfo.platform,
      user_type: userInfo.userType
    }
  }
  return config
})

// 响应拦截
http.interceptors.response.use(
  res => {
    if (res.data.code === 0) {
      ElMessage.error(res.data.msg)
    }
    return res.data
  },
  error => {
    if (error.response.status === 401) {
      const urlParams = new URLSearchParams(window.location.search)
      const sessionId = urlParams.get('sessionId') || ''
      const userId = urlParams.get('userId') || ''
      if ((sessionId && userId) || !urlParams) {
        return
      }
      if (location.pathname.includes('pad-graph')) {
        return
      }
      debounce(() => {
        useAuthStore().resetAllStates(true)
        router.push('/login')
      }, 200)
    }
  }
)

export default http
